package com.example.shopping_web_back.controller;

import com.example.shopping_web_back.pojo.GoodsDetails;
import com.example.shopping_web_back.pojo.Result;
import com.example.shopping_web_back.service.GoodsDetailsService;
import com.example.shopping_web_back.utils.ThreadLocalUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/GoodsDetail")
@Validated
public class GoodsDetailsController {

    @Autowired
    private GoodsDetailsService goodsDetailsService;

    private static final String CURRENT_PATH = System.getProperty("user.dir");
    private static final String IMAGE_DIR = CURRENT_PATH + "/uploads/image/goods/goodsDetails/";

    @PostMapping("/getGoodsDetails")
    public Result<List<GoodsDetails>> getGoodsDetails(@RequestParam("ID") Integer id) {
        List<GoodsDetails> goodsDetailsList = goodsDetailsService.getGoodsDetails(id);
        return Result.success(goodsDetailsList);
    }

    @PostMapping("/uploadDetailsImage")
    public Result uploadDetailsImage(@RequestParam("file")MultipartFile Image) throws IOException {
        Map<String, Object> map = ThreadLocalUtil.get();
        String businessName = (String) map.get("Business_name");
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String originalFileName = Image.getOriginalFilename();
        String fileExtension = "";
        if(originalFileName != null && originalFileName.lastIndexOf('.') > 0) {
            fileExtension = originalFileName.substring(originalFileName.lastIndexOf('.'));
        }
        File dir = new File(IMAGE_DIR);
        String fileName = businessName + "_" +timestamp + fileExtension;
        Path filePath = Paths.get(IMAGE_DIR + fileName);
        Files.copy(Image.getInputStream(), filePath);
        return Result.success("http://8.138.173.30:8080/image/goods/goodsDetails/" + fileName);
    }

    @Data
    // 定义一个新的对象，主要用于存储传进来的图片参数
    public static class GoodsDetailsImage {
        private List<String> goodsDetailsImage;
    }

    //更新文件名字
    public void renameFile(String oldFileName, String newFileName) throws IOException {
        File dir = new File(IMAGE_DIR);
        File fileToReName = new File(dir, oldFileName);
        if(fileToReName.exists()) {
            File renameFile = new File(dir, newFileName);
            boolean success = fileToReName.renameTo(renameFile);
            if(!success) {
                throw new IOException("Failed to rename file to " + newFileName);
            }
        }
    }

    @PostMapping("/add")
    public Result addGoodsDetails(@RequestBody GoodsDetailsImage goodsDetailsImage, @RequestParam("ID") Integer id) throws IOException {
        //此处需要完成两个操作：第一个是把传过来的图片存进去，第二个则是在本地文件夹要更新那些图片的名字
        //由于传过来的图片可能不止一张，因此要用数组去存储传过来的图片的链接，在根据链接得到要存的是哪些图片
        List<String> goodsDetailsImageUrl = goodsDetailsImage.getGoodsDetailsImage(); //存储要添加的所有图片地址
        for(int i = 0; i < goodsDetailsImageUrl.size(); i++)
        {
            //遍历所有图片，对每个图片进行重命名并存进数据库
            String fileName = goodsDetailsImageUrl.get(i).substring(goodsDetailsImageUrl.get(i).lastIndexOf('/') + 1);
            String newFileName = fileName.substring(0, fileName.lastIndexOf('.')) + "_" + id + "_" + i + fileName.substring(fileName.lastIndexOf('.'));
            renameFile(fileName, newFileName);
            goodsDetailsService.addGoodsDetails(id, "http://8.138.173.30:8080/image/goods/goodsDetails/" + newFileName);
        }
        return Result.success();
    }

    @PostMapping("/delete")
    public Result deleteGoodsDetails(@RequestParam String goodsDetailsImage) throws IOException {
        String fileName = goodsDetailsImage.substring(goodsDetailsImage.lastIndexOf('/') + 1); //获取文件名
        //先删除图片
        File dir = new File(IMAGE_DIR);
        File fileToDelete = new File(dir, fileName);
        Files.delete(fileToDelete.toPath());
        //然后删除数据库里面的记录
        goodsDetailsService.deleteGoodsDetail(goodsDetailsImage);
        return Result.success();
    }

    @PostMapping("/deleteAll")
    public Result deleteGoodsAllDetails(@RequestParam Integer id) throws IOException {
        List<GoodsDetails> listToDelete = goodsDetailsService.getGoodsDetails(id);
        File dir = new File(IMAGE_DIR);
        for (GoodsDetails goodsDetails : listToDelete) {
            String fileName = goodsDetails.getGoodsDetail().substring(goodsDetails.getGoodsDetail().lastIndexOf('/'));
            File file = new File(dir, fileName);
            Files.delete(file.toPath());
            goodsDetailsService.deleteGoodsDetail(goodsDetails.getGoodsDetail());
        }
        return Result.success();
    }

    @PostMapping("/change")
    public Result changeGoodsDetails(@RequestBody GoodsDetailsImage goodsDetailsImage, @RequestParam("ID") Integer id) throws IOException {
        //修改商品详细信息主要流程有：1.首先分两种，第一种是直接在现有基础上又添加了，第二种则是删除了一部分图片，然后又新增了（或者仅仅删除）
        List<String> goodsDetailsImageUrl =  goodsDetailsImage.getGoodsDetailsImage();
        GoodsDetails oldGoodsDetails = new GoodsDetails(), newGoodsDetails = new GoodsDetails();
        oldGoodsDetails.setGoodsId(id);
        newGoodsDetails.setGoodsId(id);
        //遍历所有传进来的图片，先看看这个图片是不是已经存在了的
        for(int i = 0; i < goodsDetailsImageUrl.size(); i++)
        {
            //要查看该图片是否是已经存在的，只需要看他最后一个_后面是第几张图片(1位)还是时间戳(14位)即可
            String fileNameInteger = goodsDetailsImageUrl.get(i).substring(goodsDetailsImageUrl.get(i).lastIndexOf('_') + 1, goodsDetailsImageUrl.get(i).lastIndexOf('.'));
            String fileName = goodsDetailsImageUrl.get(i).substring(goodsDetailsImageUrl.get(i).lastIndexOf('/') + 1);
            if(fileNameInteger.length() == 1)
            {
                //如果是1位，那么说明已经存在，那么只需要判断它的位置是否正确即可
                if(Integer.parseInt(fileNameInteger) != i) {
                    //如果不是，那么要将该图片重新命名并存储到数据库里面
                    String newFileName = fileName.substring(0, fileName.lastIndexOf('_')) + "_" + i + fileName.substring(fileName.lastIndexOf('.'));
                    renameFile(fileName, newFileName);
                    oldGoodsDetails.setGoodsDetail(goodsDetailsImageUrl.get(i));
                    newGoodsDetails.setGoodsDetail("http://8.138.173.30:8080/image/goods/goodsDetails/" + newFileName);
                    goodsDetailsService.changeGoodsDetails(oldGoodsDetails, newGoodsDetails);
                }
            }else {
                //如果不是一位，那么就不存在，要存进数据库里面，具体流程：文件改名——存进数据库
                //获取文件名
                String newFileName = fileName.substring(0, fileName.lastIndexOf('.')) + "_" + id + "_" + i + fileName.substring(fileName.lastIndexOf('.'));
                renameFile(fileName, newFileName);
                goodsDetailsService.addGoodsDetails(id, "http://8.138.173.30:8080/image/goods/goodsDetails/" + newFileName);
            }
        }
        return Result.success();
    }
}
